package greedy;

/**
 * 不重叠的区间个数
 * <p>
 * 题目描述：计算让一组区间不重叠所需要移除的区间个数。
 * <p>
 * 先计算最多能组成的不重叠区间个数，然后用区间总个数减去不重叠区间的个数。
 * <p>
 * 在每次选择中，区间的结尾最为重要，选择的区间结尾越小，留给后面的区间的空间越大，
 * 那么后面能够选择的区间个数也就越大。
 * <p>
 * 按区间的结尾进行排序，每次选择结尾最小，并且和前一个区间不重叠的区间。
 * <p>
 * <p>
 * Input: [ [1,2], [1,2], [1,2] ]
 * <p>
 * Output: 2
 * <p>
 * Explanation: You need to remove two [1,2] to make the rest of intervals non-overlapping.
 * <p>
 * <p>
 * Input: [ [1,2], [2,3] ]
 * <p>
 * Output: 0
 * <p>
 * Explanation: You don't need to remove any of the intervals since they're already non-overlapping.
 */
public class NonOverlappingIntervals {


    public static void main(String[] args) {

        int[][] activity = new int[][]{
                //new int[]{0, 0},
                new int[]{1, 2},
                new int[]{1, 2},
                new int[]{1, 2}
        };
        int result = eraseOverlapIntervals(activity);

        System.out.println(activity.length - result);
    }

    public static int eraseOverlapIntervals(int[][] intervals) {
        // 已选择的活动的index下标
        int selectAbleActivityIndex = 0;

        for (int activityIndex = 1; activityIndex < intervals.length; activityIndex++) {

            int[] interval = intervals[activityIndex];

            if (interval[0] >= intervals[selectAbleActivityIndex][1]) {

                selectAbleActivityIndex++;

            }


        }


        return selectAbleActivityIndex + 1;
    }
}
